package cc.owoo.godpen.reflect;

import cc.owoo.godpen.analysis.json.Json;
import cc.owoo.godpen.util.N;

import java.lang.reflect.Array;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.util.*;

/**
 * 类型转换器，用于反射时的类型转换
 * Created by nimensei
 * 2022-05-16 下午 04:34
 **/
public class Translate {
    private static final HashMap<Type, TypeTranslateCache> translateCache = new HashMap<>();// 缓存的类型转换器

    /**
     * 基本数据类型转换器
     */
    private static final HashMap<Class<?>, TypeTranslate> base = new HashMap<>() {{
        put(char.class, (object, original) -> object == null ? original : parseChar(object));
        put(boolean.class, (object, original) -> object == null ? original : parseBoolean(object));
        put(byte.class, (object, original) -> object == null ? original : parseByte(object));
        put(short.class, (object, original) -> object == null ? original : parseShort(object));
        put(int.class, (object, original) -> object == null ? original : parseInt(object));
        put(long.class, (object, original) -> object == null ? original : parseLong(object));
        put(float.class, (object, original) -> object == null ? original : parseFloat(object));
        put(double.class, (object, original) -> object == null ? original : parseDouble(object));
        put(Character.class, (object, original) -> notNull(parseCharacterObject(object), original));
        put(Boolean.class, (object, original) -> notNull(parseBooleanObject(object), original));
        put(Byte.class, (object, original) -> notNull(parseByteObject(object), original));
        put(Short.class, (object, original) -> notNull(parseShortObject(object), original));
        put(Integer.class, (object, original) -> notNull(parseIntObject(object), original));
        put(Long.class, (object, original) -> notNull(parseLongObject(object), original));
        put(Float.class, (object, original) -> notNull(parseFloatObject(object), original));
        put(Double.class, (object, original) -> notNull(parseDoubleObject(object), original));
        put(BigInteger.class, (object, original) -> notNull(parseBigInteger(object), original));
        put(BigDecimal.class, (object, original) -> notNull(parseBigDecimal(object), original));
        put(String.class, (object, original) -> notNull(parseString(object), original));
        put(StringBuffer.class, (object, original) -> notNull(parseStringBuffer(object), original));
        put(StringBuilder.class, (object, original) -> notNull(parseStringBuilder(object), original));
        put(Date.class, (object, original) -> notNull(parseDate(object), original));
    }};

    private static Object notNull(Object a, Object b) {
        return a == null ? b : a;
    }

    /**
     * 集合创建器
     */
    private static final HashMap<Class<?>, CollectionCreate> collectionCreate = new HashMap<>() {{
        put(LinkedList.class, Translate::createLinkedList);
        put(ArrayList.class, Translate::createArrayList);
        put(HashSet.class, Translate::createHashSet);
        put(LinkedHashSet.class, Translate::createLinkedHashSet);
        put(Vector.class, Translate::createVector);
        put(List.class, Translate::createArrayList);
        put(Set.class, Translate::createHashSet);
        put(Queue.class, Translate::createLinkedList);
        put(Collection.class, Translate::createArrayList);
        put(AbstractList.class, Translate::createArrayList);
        put(AbstractSet.class, Translate::createHashSet);
        put(AbstractCollection.class, Translate::createArrayList);
    }};

    /**
     * 键值对创建器
     */
    private static final HashMap<Class<?>, MapCreate> mapCreate = new HashMap<>() {{
        put(Map.class, Translate::createHashMap);
        put(HashMap.class, Translate::createHashMap);
        put(LinkedHashMap.class, Translate::createLinkedHashMap);
        put(Hashtable.class, Translate::createHashtable);
    }};

    /**
     * 对象类型转换
     *
     * @param object      需要转换的对象
     * @param targetClass 目标类型
     * @return 如果转换成功则返回转换的结果，否则返回null
     */
    public static <T> T translate(Object object, Class<T> targetClass) {
        return (T) translate(object, (Type) targetClass);
    }

    /**
     * 对象类型转换，实例化一个class并转换数据
     *
     * @param object     需要转换的对象
     * @param targetType 目标类型
     * @return 如果转换成功则返回转换的结果，否则返回null
     */
    public static Object translate(Object object, Type targetType) {
        TypeTranslate translate = createTranslate(targetType);
        if (translate == null)
            return null;
        return translate.parse(object, null);
    }

    /**
     * 填充数据，将数据填充到已有的实例化对象中
     *
     * @param original 被填充的实例化对象（可为null）
     * @param data     需要填充的对象（可为null）
     * @return 如果填充成功则返回转换的结果，否则返回null
     */
    public static Object fill(Object original, Object data) {
        if (original == data || original == null)
            return data;
        if (data == null)
            return original;
        TypeTranslate translate = createTranslate(original.getClass());
        if (translate == null)
            return null;
        return translate.parse(data, original);
    }

    /**
     * 创建类型转换器
     *
     * @param type 目标类型
     * @return 类型转换器
     */
    static TypeTranslate createTranslate(Type type) {
        TypeTranslateCache cache = createTranslateIfCache(type);
        return cache == null ? null : cache.translate;
    }

    /**
     * 创建类型转换器，并在缓存中进行记录
     *
     * @param type 目标类型
     * @return 类型转换器
     */
    private static TypeTranslateCache createTranslateIfCache(Type type) {
        if (type == null)
            return null;
        synchronized (ReflectLock.lock) {
            TypeTranslateCache cache = translateCache.get(type);
            if (cache != null)
                return cache;
            cache = new TypeTranslateCache();
            translateCache.put(type, cache);
            cache.translate = buildTranslate(type);
            if (cache.translate == null) {
                translateCache.remove(type);
                return null;
            }
            return cache;
        }
    }

    /**
     * 构建新的类型转换器
     *
     * @param type 目标类型
     * @return 类型转换器
     */
    private static TypeTranslate buildTranslate(Type type) {
        if (type == null)
            throw new NullPointerException("类型不能为空");
        ClassType classType = ClassType.create(type);
        if (classType == null)
            return null;
        synchronized (ReflectLock.lock) {
            Class<?> rowType = classType.rowType();
            ParameterizedType parameterized = classType.parameterizedType();
            TypeTranslate valueTranslate = base.get(rowType);
            if (valueTranslate != null)
                return valueTranslate;
            if (Json.class.isAssignableFrom(rowType))
                return ((object, original) -> {
                    if (original == null)
                        return Json.create(object);
                    return ((Json) original).fill(object) ? original : Json.create(object);
                });
            if (rowType.isArray()) {
                TypeTranslateCache arrayValueTranslate = createTranslateIfCache(rowType.componentType());
                if (arrayValueTranslate == null)
                    return null;
                return (object, original) -> translateArray(object, rowType, original, arrayValueTranslate);
            }
            CollectionCreate collection = collectionCreate.get(rowType);
            if (collection != null)
                return createCollectionTranslate(collection, parameterized);
            MapCreate map = mapCreate.get(rowType);
            if (map != null)
                return createMapTranslate(map, parameterized);
            if (rowType.getSuperclass() == null)
                return (object, targetObject) -> object;
            ObjectReflect<Object> reflect = ObjectReflectBuild.create((Class<Object>) rowType);
            return (object, original) -> translateObject(object, original, reflect);
        }
    }

    /**
     * 创建集合类型的转换器
     *
     * @param collectionCreate 集合对象创建器
     * @param parameterized    参数类型
     * @return 类型转换器
     */
    private static TypeTranslate createCollectionTranslate(CollectionCreate collectionCreate, ParameterizedType parameterized) {
        TypeTranslateCache genericTranslate;
        if (parameterized != null) {
            Type[] types = parameterized.getActualTypeArguments();
            if (types.length != 1)
                return null;
            genericTranslate = createTranslateIfCache(types[0]);
            if (genericTranslate == null)
                return null;
        } else
            genericTranslate = null;
        return (object, originalObject) -> {
            var newCollection = parseArray(object);
            if (newCollection == null)
                return originalObject;
            Collection<Object> collection = originalObject == null ? collectionCreate.create(newCollection.size()) : (Collection<Object>) originalObject;
            ArrayList<Object> originalCollection = new ArrayList<>(collection);
            collection.clear();
            int len = Math.max(originalCollection.size(), newCollection.size());
            for (int i = 0; i < len; i++) {
                Object original = i < originalCollection.size() ? originalCollection.get(i) : null;
                Object value = i < newCollection.size() ? newCollection.get(i) : null;
                if (value == null) {
                    collection.add(original);
                    continue;
                }
                if (genericTranslate != null)
                    value = genericTranslate.translate.parse(value, original);
                else {
                    TypeTranslateCache typeTranslate = createTranslateIfCache(value.getClass());
                    if (typeTranslate == null)
                        continue;
                    value = typeTranslate.translate.parse(value, original);
                }
                collection.add(value);
            }
            for (Object obj : collection)
                if (obj != null)
                    return collection;
            return null;
        };
    }

    /**
     * 创建键值对类型的转换器
     *
     * @param mapCreate     键值对创建器
     * @param parameterized 参数类型
     * @return 类型转换器
     */
    private static TypeTranslate createMapTranslate(MapCreate mapCreate, ParameterizedType parameterized) {
        TypeTranslateCache keyGenericTranslate;
        TypeTranslateCache valueGenericTranslate;
        if (parameterized != null) {
            Type[] types = parameterized.getActualTypeArguments();
            if (types.length != 2)
                return null;
            keyGenericTranslate = createTranslateIfCache(types[0]);
            valueGenericTranslate = createTranslateIfCache(types[1]);
            if (keyGenericTranslate == null || valueGenericTranslate == null)
                return null;
        } else {
            keyGenericTranslate = null;
            valueGenericTranslate = null;
        }
        return (object, originalObject) -> {
            if (object == null)
                return originalObject;
            var newMap = parseMap(object);
            if (newMap == null)
                return originalObject;
            Map<Object, Object> originalMap = originalObject == null ? mapCreate.create() : (Map<Object, Object>) originalObject;
            for (var entry : newMap.entrySet()) {
                Object key = entry.getKey();
                Object value = entry.getValue();
                Object original = originalMap.get(key);
                if (keyGenericTranslate != null)
                    keyGenericTranslate.translate.parse(key, null);
                if (valueGenericTranslate != null)
                    value = valueGenericTranslate.translate.parse(value, original);
                else if (value != null) {
                    TypeTranslateCache typeTranslate = createTranslateIfCache(value.getClass());
                    if (typeTranslate == null)
                        continue;
                    typeTranslate.translate.parse(value, original);
                }
                if (key == null || value == original)
                    continue;
                originalMap.put(key, value);
            }
            for (var entry : originalMap.entrySet())
                if (entry.getValue() != null)
                    return originalMap;
            return null;
        };
    }

    /**
     * 尝试将值转换为对象
     *
     * @param value         需要转换的值
     * @param original      原来的值
     * @param objectReflect 对象值反射
     * @return 对象
     */
    private static Object translateObject(Object value, Object original, ObjectReflect<Object> objectReflect) {
        var map = parseMap(value);
        if (map == null)
            return original;
        if (original == null)
            return objectReflect.newInstance(map);
        objectReflect.fillInstance(map, original);
        return original;
    }

    /**
     * 尝试将值转换为数组类型，仅支持一维数组，多维数组需要自行递归调用
     *
     * @param value          需要转换的值
     * @param targetType     转换后的数组类型，请传入转换后的数组的class，如int[].class
     * @param valueTranslate 值转换器
     * @return 数组对象
     */
    private static Object translateArray(Object value, Class<?> targetType, Object originalObject, TypeTranslateCache valueTranslate) {
        if (value == null)
            return originalObject;
        if (value.getClass() == targetType)
            return value;
        var list = parseArray(value);
        if (list == null)
            return originalObject;
        Class<?> componentType = targetType.componentType();
        Object array;
        if (originalObject == null)
            array = Array.newInstance(componentType, list.size());
        else {
            int length = Array.getLength(originalObject);
            if (length < list.size()) {
                array = Array.newInstance(componentType, list.size());
                System.arraycopy(originalObject, 0, array, 0, length);
            } else
                array = originalObject;
        }
        int index = 0;
        for (Object item : list) {
            try {
                Object original = Array.get(array, index);
                Object v = valueTranslate.translate.parse(item, original);
                if (v == null)
                    continue;
                Array.set(array, index, v);
            } catch (Exception ignored) {
            }
            ++index;
        }
        int length = Array.getLength(array);
        for (int i = 0; i < length; i++)
            if (Array.get(array, i) != null)
                return array;
        return null;
    }

    /**
     * 删除数字字符串的小数部分
     *
     * @param string 需要删除的字符串
     */
    private static String removeFixed(String string) {
        int index = string.indexOf('.');
        return index == -1 ? string : string.substring(0, index);
    }

    /**
     * 尝试将值转换为char类型
     *
     * @param value 需要转换的值
     * @return 转换结果，如果转换失败则返回null
     */
    public static char parseChar(Object value) {
        Character translateValue = parseCharacterObject(value);
        return translateValue == null ? '\0' : translateValue;
    }

    /**
     * 尝试将值转换为boolean类型
     *
     * @param value 需要转换的值
     * @return 转换结果，如果转换失败则返回null
     */
    public static boolean parseBoolean(Object value) {
        Boolean translateValue = parseBooleanObject(value);
        return translateValue != null && translateValue;
    }

    /**
     * 尝试将值转换为byte类型
     *
     * @param value 需要转换的值
     * @return 转换结果，如果转换失败则返回null
     */
    public static byte parseByte(Object value) {
        Byte translateValue = parseByteObject(value);
        return translateValue == null ? 0 : translateValue;
    }

    /**
     * 尝试将值转换为short类型
     *
     * @param value 需要转换的值
     * @return 转换结果，如果转换失败则返回null
     */
    public static short parseShort(Object value) {
        Short translateValue = parseShortObject(value);
        return translateValue == null ? 0 : translateValue;
    }


    /**
     * 尝试将值转换为int类型
     *
     * @param value 需要转换的值
     * @return 转换结果，如果转换失败则返回null
     */
    public static int parseInt(Object value) {
        Integer translateValue = parseIntObject(value);
        return translateValue == null ? 0 : translateValue;
    }

    /**
     * 尝试将值转换为long类型
     *
     * @param value 需要转换的值
     * @return 转换结果，如果转换失败则返回null
     */
    public static long parseLong(Object value) {
        Long translateValue = parseLongObject(value);
        return translateValue == null ? 0 : translateValue;
    }

    /**
     * 尝试将值转换为float类型
     *
     * @param value 需要转换的值
     * @return 转换结果，如果转换失败则返回null
     */
    public static float parseFloat(Object value) {
        Float translateValue = parseFloatObject(value);
        return translateValue == null ? 0 : translateValue;
    }

    /**
     * 尝试将值转换为double类型
     *
     * @param value 需要转换的值
     * @return 转换结果，如果转换失败则返回null
     */
    public static double parseDouble(Object value) {
        Double translateValue = parseDoubleObject(value);
        return translateValue == null ? 0 : translateValue;
    }

    /**
     * 尝试将值转换为Character类型
     *
     * @param value 需要转换的值
     * @return 转换结果，如果转换失败则返回null
     */
    public static Character parseCharacterObject(Object value) {
        if (value == null)
            return null;
        if (value instanceof Character character)
            return character;
        if (value instanceof Number number)
            return (char) number.intValue();
        if (value instanceof CharSequence charSequence) {
            String string = charSequence.toString().trim();
            if (string.length() == 1)
                return string.charAt(0);
            else
                try {
                    return (char) Integer.parseInt(string);
                } catch (NumberFormatException ignored) {
                }
        }
        return null;
    }

    /**
     * 尝试将值转换为Boolean类型
     *
     * @param value 需要转换的值
     * @return 转换结果，如果转换失败则返回null
     */
    public static Boolean parseBooleanObject(Object value) {
        if (value == null)
            return null;
        if (value instanceof Boolean bool)
            return bool;
        if (value instanceof CharSequence)
            return (value.toString()).equals("true");
        return false;
    }

    /**
     * 尝试将值转换为Byte类型
     *
     * @param value 需要转换的值
     * @return 转换结果，如果转换失败则返回null
     */
    public static Byte parseByteObject(Object value) {
        if (value == null)
            return null;
        if (value instanceof Byte number)
            return number;
        if (value instanceof Number number)
            return number.byteValue();
        if (value instanceof Character character)
            return (byte) character.charValue();
        if (value instanceof CharSequence)
            try {
                return new BigDecimal(value.toString()).byteValue();
            } catch (Exception ignored) {
            }
        return null;
    }

    /**
     * 尝试将值转换为Short类型
     *
     * @param value 需要转换的值
     * @return 转换结果，如果转换失败则返回null
     */
    public static Short parseShortObject(Object value) {
        if (value == null)
            return null;
        if (value instanceof Short number)
            return number;
        if (value instanceof Number number)
            return number.shortValue();
        if (value instanceof Character character)
            return (short) character.charValue();
        if (value instanceof CharSequence)
            try {
                return new BigDecimal(value.toString()).shortValue();
            } catch (Exception ignored) {
            }
        return null;
    }

    /**
     * 尝试将值转换为Integer类型
     *
     * @param value 需要转换的值
     * @return 转换结果，如果转换失败则返回null
     */
    public static Integer parseIntObject(Object value) {
        if (value == null)
            return null;
        if (value instanceof Integer number)
            return number;
        if (value instanceof Number number)
            return number.intValue();
        if (value instanceof Character character)
            return (int) character;
        if (value instanceof CharSequence)
            try {
                return new BigDecimal(value.toString()).intValue();
            } catch (Exception ignored) {
            }
        return null;
    }

    /**
     * 尝试将值转换为Long类型
     *
     * @param value 需要转换的值
     * @return 转换结果，如果转换失败则返回null
     */
    public static Long parseLongObject(Object value) {
        if (value == null)
            return null;
        if (value instanceof Long number)
            return number;
        if (value instanceof Number number)
            return number.longValue();
        if (value instanceof Date date)
            return date.getTime();
        if (value instanceof Character character)
            return (long) character;
        if (value instanceof CharSequence)
            try {
                return new BigDecimal(value.toString()).longValue();
            } catch (Exception ignored) {
            }
        return null;
    }

    /**
     * 尝试将值转换为Float类型
     *
     * @param value 需要转换的值
     * @return 转换结果，如果转换失败则返回null
     */
    public static Float parseFloatObject(Object value) {
        if (value == null)
            return null;
        if (value instanceof Float number)
            return number;
        if (value instanceof Number number)
            return number.floatValue();
        if (value instanceof Character character)
            return (float) character;
        if (value instanceof CharSequence)
            try {
                return Float.valueOf(value.toString());
            } catch (Exception ignored) {
            }
        return null;
    }

    /**
     * 尝试将值转换为Double类型
     *
     * @param value 需要转换的值
     * @return 转换结果，如果转换失败则返回null
     */
    public static Double parseDoubleObject(Object value) {
        if (value == null)
            return null;
        if (value instanceof Double number)
            return number;
        if (value instanceof Number number)
            return number.doubleValue();
        if (value instanceof Character character)
            return (double) character;
        if (value instanceof CharSequence)
            try {
                return Double.valueOf(value.toString());
            } catch (Exception ignored) {
            }
        return null;
    }

    /**
     * 尝试将值转换为BigInteger类型
     *
     * @param value 需要转换的值
     * @return 转换结果，如果转换失败则返回null
     */
    public static BigInteger parseBigInteger(Object value) {
        if (value instanceof BigInteger integer)
            return integer;
        if (value instanceof BigDecimal decimal)
            return decimal.toBigInteger();
        if (value instanceof Character character)
            return new BigInteger(String.valueOf((int) character));
        if (value instanceof Number number)
            try {
                new BigInteger(String.valueOf(number.longValue()));
            } catch (Exception ignored) {
            }
        if (value instanceof CharSequence)
            try {
                new BigInteger(value.toString());
            } catch (Exception ignored) {
            }
        return null;
    }

    /**
     * 尝试将值转换为BigDecimal类型
     *
     * @param value 需要转换的值
     * @return 转换结果，如果转换失败则返回null
     */
    public static BigDecimal parseBigDecimal(Object value) {
        if (value instanceof BigDecimal decimal)
            return decimal;
        if (value instanceof BigInteger integer)
            return new BigDecimal(integer);
        if (value instanceof Character character)
            return new BigDecimal(String.valueOf((int) character));
        if (value instanceof Number number)
            try {
                new BigDecimal(String.valueOf(number.doubleValue()));
            } catch (Exception ignored) {
            }
        if (value instanceof CharSequence)
            try {
                new BigDecimal(value.toString());
            } catch (Exception ignored) {
            }
        return null;
    }

    /**
     * 尝试将值转换为String类型
     *
     * @param value 需要转换的值
     * @return 转换结果，如果转换失败则返回null
     */
    public static String parseString(Object value) {
        if (value == null)
            return null;
        if (value instanceof String string)
            return string;
        if (value instanceof CharSequence || value instanceof Boolean || value instanceof Character || value instanceof Number)
            return value.toString();
        return Json.stringify(value);
    }

    /**
     * 尝试将值转换为StringBuffer类型
     *
     * @param value 需要转换的值
     * @return 转换结果，如果转换失败则返回null
     */
    public static StringBuffer parseStringBuffer(Object value) {
        if (value == null)
            return null;
        if (value instanceof StringBuffer stringBuffer)
            return stringBuffer;
        if (value instanceof CharSequence || value instanceof Boolean || value instanceof Character || value instanceof Number)
            return new StringBuffer(value.toString());
        return new StringBuffer(Json.stringify(value));
    }

    /**
     * 尝试将值转换为StringBuilder类型
     *
     * @param value 需要转换的值
     * @return 转换结果，如果转换失败则返回null
     */
    public static StringBuilder parseStringBuilder(Object value) {
        if (value == null)
            return null;
        if (value instanceof StringBuilder stringBuilder)
            return stringBuilder;
        if (value instanceof CharSequence || value instanceof Boolean || value instanceof Character || value instanceof Number)
            return new StringBuilder(value.toString());
        return new StringBuilder(Json.stringify(value));
    }

    /**
     * 尝试将值转换为Date类型
     *
     * @param value 需要转换的值
     * @return 转换结果，如果转换失败则返回null
     */
    public static Date parseDate(Object value) {
        if (value instanceof Date date)
            return date;
        if (value instanceof Number number)
            return new Date(number.longValue());
        if (value instanceof CharSequence charSequence)
            try {
                return N.dateFormat.parse(charSequence.toString());
            } catch (ParseException ignored) {
            }
        return null;
    }

    /**
     * 尝试将对象转换成数组列表
     *
     * @param object 需要转换的对象
     * @return 转换后的数组列表，如果转换失败则返回null
     */
    public static ArrayList<Object> parseArray(Object object) {
        if (object == null)
            return null;
        if (object instanceof ArrayList<?> list)
            return (ArrayList<Object>) list;
        if (object.getClass().isArray()) {
            try {
                int length = Array.getLength(object);
                ArrayList<Object> list = new ArrayList<>(length);
                for (int i = 0; i < length; i++)
                    list.add(Array.get(object, i));
                return list;
            } catch (Exception e) {
                return null;
            }
        }
        if (object instanceof Collection<?> collection)
            return new ArrayList<>(collection);
        if (object instanceof CharSequence string)
            return parseArray(string);
        return null;
    }

    /**
     * 如果字符串为Json数据，则尝试将字符串转换成列表
     *
     * @param charSequence 需要转换的Json字符串
     * @return 转换后的数组列表，如果转换失败则返回null
     */
    public static ArrayList<Object> parseArray(CharSequence charSequence) {
        if (charSequence == null)
            return null;
        String string = with(charSequence.toString(), '[', ']');
        if (string == null)
            return null;
        ArrayList<Object> arrayList = Json.parse(string).getArrayList();
        return arrayList == null || arrayList.size() == 0 ? null : arrayList;
    }

    /**
     * 将键值对或者对象转换成键值对，转换后的键值对类型为String: Object
     *
     * @param object 需要转换的对象
     * @return 转换后的键值对，类型为String: Object
     */
    public static HashMap<String, Object> parseMap(Object object) {
        if (object == null || object instanceof Number || object instanceof Collection<?> || object instanceof Boolean || object.getClass().isArray())
            return null;
        if (object instanceof Map<?, ?> map) {
            HashMap<String, Object> res = new HashMap<>();
            map.forEach((key, value) -> {
                if (key == null)
                    return;
                res.put(key.toString(), value);
            });
            return res;
        }
        if (object instanceof CharSequence string)
            return parseMap(string);
        return ObjectReflectBuild.create(object.getClass()).getHashMap(object);
    }


    /**
     * 如果字符串为Json数据，则尝试将字符串转换成键值对
     *
     * @param charSequence 需要转换的Json字符串
     * @return 转换后的键值对，类型为String: Object
     */
    public static HashMap<String, Object> parseMap(CharSequence charSequence) {
        if (charSequence == null)
            return null;
        String string = with(charSequence.toString(), '{', '}');
        if (string == null)
            return null;
        HashMap<String, Object> hashMap = Json.parse(string).getHashMap();
        return hashMap == null || hashMap.size() == 0 ? null : hashMap;
    }

    /**
     * 判断第一个非空字符和最后一个非空字符是否符合条件
     *
     * @param string 需要判断的字符串
     * @param start  匹配第一个非空字符
     * @param end    匹配最后一个非空字符
     * @return 如果符合则返回符合条件的字符串，否则返回null
     */
    static String with(String string, char start, char end) {
        int before = -1;
        while (++before < string.length()) {
            char c = string.charAt(before);
            if (c <= 32 || c == '\'' || c == '"')
                continue;
            if (c != start)
                return null;
            break;
        }
        int after = string.length();
        while (--after > before) {
            char c = string.charAt(after);
            if (c <= 32 || c == '\'' || c == '"')
                continue;
            if (c != end)
                return null;
            break;
        }
        return string.substring(before, after);
    }

    /**
     * 创建LinkedList对象
     *
     * @param length 初始化长度
     * @param <T>    泛型类型
     * @return LinkedList对象
     */
    public static <T> LinkedList<T> createLinkedList(int length) {
        return new LinkedList<>();
    }

    /**
     * 创建ArrayList对象
     *
     * @param length 初始化长度
     * @param <T>    泛型类型
     * @return ArrayList对象
     */
    public static <T> ArrayList<T> createArrayList(int length) {
        return new ArrayList<>(length);
    }

    /**
     * 创建HashSet对象
     *
     * @param length 初始化长度
     * @param <T>    泛型类型
     * @return HashSet对象
     */
    public static <T> HashSet<T> createHashSet(int length) {
        return new HashSet<>(length);
    }

    /**
     * 创建LinkedHashSet对象
     *
     * @param length 初始化长度
     * @param <T>    泛型类型
     * @return LinkedHashSet对象
     */
    public static <T> LinkedHashSet<T> createLinkedHashSet(int length) {
        return new LinkedHashSet<>(length);
    }

    /**
     * 创建Vector对象
     *
     * @param length 初始化长度
     * @param <T>    泛型类型
     * @return Vector对象
     */
    public static <T> Vector<T> createVector(int length) {
        return new Vector<>(length);
    }

    /**
     * 创建HashMap对象
     *
     * @param <K> 键类型
     * @param <V> 值类型
     * @return HashMap对象
     */
    public static <K, V> HashMap<K, V> createHashMap() {
        return new HashMap<>();
    }

    /**
     * 创建LinkedHashMap对象
     *
     * @param <K> 键类型
     * @param <V> 值类型
     * @return LinkedHashMap对象
     */
    public static <K, V> LinkedHashMap<K, V> createLinkedHashMap() {
        return new LinkedHashMap<>();
    }

    /**
     * 创建Hashtable对象
     *
     * @param <K> 键类型
     * @param <V> 值类型
     * @return Hashtable对象
     */
    public static <K, V> Hashtable<K, V> createHashtable() {
        return new Hashtable<>();
    }

    /**
     * 键值对
     *
     * @param key   键
     * @param value 值
     */
    public record MapEntry(String key, Object value) {
    }

    private interface ArrayGet {
        Object get(int index);
    }

    /**
     * 数组迭代器
     */
    public interface CollectionIterable extends Iterable<Object> {
        /**
         * 获取数组长度
         *
         * @return 数组长度
         */
        int length();
    }

    /**
     * 类型转换器缓存对象
     */
    private static class TypeTranslateCache {
        public TypeTranslate translate;
    }
}
